﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Scribd.Net;

namespace DemoApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Properties.Settings.Default.APIKey))
            {
                OptionsDialog _options = new OptionsDialog();
                if (_options.ShowDialog(this) == DialogResult.Cancel)
                {
                    Application.Exit();
                }
            }


            SetupServiceCreds();

            this.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
            this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
            this.toolStripStatusLabel1.Text = "Ready.";
        }

        private void SetupServiceCreds()
        {
            // Set up credentials
            Scribd.Net.Service.APIKey = Properties.Settings.Default.APIKey;
            Scribd.Net.Service.SecretKey = Properties.Settings.Default.SecretKey;
            Scribd.Net.Service.PublisherID = Properties.Settings.Default.PublisherID;
            Scribd.Net.Service.EnforceSigning = Properties.Settings.Default.EnforceSigning;
        }

        /// <summary>
        /// Refresh
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            // Ensure we're logged in
            if (!Scribd.Net.Service.User.IsLoggedIn)
            {
                // Login user
                this.toolStripStatusLabel1.Text = "Logging into Scribd.com ...";
                Scribd.Net.User.LoginFailed += new EventHandler<UserEventArgs>(User_LoginFailed);
                Scribd.Net.User.LoggedIn += new EventHandler<UserEventArgs>(User_LoggedIn);

                Scribd.Net.User.Login(Properties.Settings.Default.Username, Properties.Settings.Default.Password);
            }
        }

        /// <summary>
        /// View Document
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            try
            {
                Document _document = GetSelectedDocument();

                if (_document != null)
                {
                    string _url = string.Empty;
                    if (_document.AccessType == AccessTypes.Private)
                    {
                        // Private has a secret password.
                        _url = string.Format(@"http://www.scribd.com/doc/{0}/?secret_password={1}",
                            _document.DocumentId.ToString(), _document.SecretPassword);
                    }
                    else
                    {
                        _url = string.Format(@"http://www.scribd.com/doc/{0}", _document.DocumentId.ToString());
                    }

                    // Runs whatever the default web browser is
                    System.Diagnostics.Process.Start(_url);
                }
            }
            catch (Exception _ex)
            {
                System.Windows.Forms.MessageBox.Show(_ex.ToString(), "Scribd Error");
            }
        }

        void User_LoggedIn(object sender, UserEventArgs e)
        {
            DownloadUserDocuments();
        }

        void User_LoginFailed(object sender, UserEventArgs e)
        {
            MessageBox.Show("Login failed.  Please verify your account information.", "Login", MessageBoxButtons.OK);
        }

        

        private void DownloadUserDocuments()
        {
            // Pull from Scribd.com
            this.toolStripStatusLabel1.Text = "Accessing Scribd.com ...";

            Scribd.Net.Service.User.ReloadDocuments();

            this.toolStripStatusLabel1.Text = string.Format("{0} documents found.", Scribd.Net.Service.User.Documents.Count.ToString());

            // Bind
            BindDocuments(Scribd.Net.Service.User.Documents);
        }

        #region Searching 

        /// <summary>
        /// Search button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;

            // Set up criteria
            Scribd.Net.Search.Criteria _criteria = new Search.Criteria();
            _criteria.Query = this.textBox1.Text;
            _criteria.Scope = SearchScope.All;
            _criteria.StartIndex = 0;
            _criteria.MaxResults = 50;

            this.toolStripStatusLabel1.Text = "Starting search ...";
            backgroundWorker1.RunWorkerAsync(_criteria);
        }
        
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundWorker1.ReportProgress(1, "Searching ...");

            // Make find call.
            e.Result = Scribd.Net.Search.Find((Scribd.Net.Search.Criteria)e.Argument);
        }

        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.toolStripStatusLabel1.Text = e.UserState.ToString();
            this.toolStripProgressBar1.Value = 1;
            this.toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
        }

        void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // Grab the result
            Scribd.Net.Search.Result _result = (Scribd.Net.Search.Result)e.Result;

            this.toolStripProgressBar1.Value = 0;
            this.toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            this.toolStripStatusLabel1.Text = string.Format("Search results: {0} documents of about {1} available.", _result.Documents.Count.ToString(), _result.TotalAvailable.ToString());
           
            // Bind documents
            BindDocuments(_result.Documents);

            button1.Enabled = true;
        }

        #endregion Searching

        private void BindDocuments(List<Scribd.Net.Document> documents)
        {
            this.listView1.FullRowSelect = true;
            this.listView1.GridLines = true;
            this.listView1.MultiSelect = false;
            this.listView1.Dock = DockStyle.Fill;
            this.listView1.View = View.LargeIcon; // View.Details;
            this.listView1.Clear();

            // Add Columns.
            //this.listView1.Columns.Clear();
            this.listView1.Columns.Add(new ColumnHeader());
            this.listView1.Columns.Add(new ColumnHeader());
            this.listView1.Columns.Add(new ColumnHeader());

            this.listView1.Columns[0].Text = "Title";
            this.listView1.Columns[1].Text = "Description";
            this.listView1.Columns[2].Text = "Access";
            
            foreach (Document _document in documents)
            {

                ListViewItem _item = new ListViewItem();

                _item.Text = _document.Title;
                _item.Tag = _document; //.DocumentId.ToString();
                _item.SubItems.Add(_document.Description);
                _item.SubItems.Add(_document.AccessType.ToString());

                imageList1.Images.Add(_document.DocumentId.ToString(), _document.ThumbnailImage);
                _item.ImageKey = _document.DocumentId.ToString();
                

                this.listView1.Items.Add(_item);
            }
        }

        private Document GetSelectedDocument()
        {
            try
            {
                if (this.listView1.SelectedItems.Count > 0)
                {
                    ListViewItem _item = this.listView1.SelectedItems[0];
                    if (null != _item)
                    {
                        Scribd.Net.Document _doc = (Scribd.Net.Document)_item.Tag;
                        return _doc;
                    }
                }
            }
            catch (Exception _ex)
            {
                System.Windows.Forms.MessageBox.Show(_ex.ToString(), "Scribd Error");
            }

            return new Document();
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            OptionsDialog _options = new OptionsDialog();
            if (_options.ShowDialog(this) == DialogResult.OK)
            {
                SetupServiceCreds();
            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            EmbedCodeDialog _dialog = new EmbedCodeDialog();
            _dialog.SetCode(GetSelectedDocument().GetEmbedCode());
            _dialog.ShowDialog(this);
        }

        // Upload file
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                Scribd.Net.Document _document = Scribd.Net.Document.Upload(openFileDialog1.FileName, AccessTypes.Public, false);
                MessageBox.Show(string.Format("Uploaded {0}", _document.Title));
                DownloadUserDocuments();
            }
        }
    }
}
